package com.txzt.gaea.common.base.wrapper;

import com.txzt.gaea.common.util.BeanKit;
import org.beetl.sql.core.engine.PageQuery;

import java.util.List;
import java.util.Map;

/**
 * 控制器查询结果的包装类基类
 *
 * @author Leo
 * @date 2017年2月13日 下午10:49:36
 */
public abstract class BaseControllerWrapper {

    public Object obj = null;

    public BaseControllerWrapper(Object obj) {
        if(obj instanceof BaseControllerWrapper){
            obj = ((BaseControllerWrapper) obj).wrap();
        }
        this.obj = obj;
    }

    @SuppressWarnings("unchecked")
    public Object wrap() {
        //分页对象
        if(this.obj instanceof PageQuery) {
            PageQuery pageQuery = (PageQuery) this.obj;
            if(pageQuery != null && pageQuery.getList() != null && !pageQuery.getList().isEmpty()){
                List<Map<String, Object>> maps;
                if(!(pageQuery.getList().get(0) instanceof Map)){
                    maps = BeanKit.listToMapList(pageQuery.getList());
                }else {
                    maps = pageQuery.getList();
                }
                wrapTheMapList(maps);
                ((PageQuery) this.obj).setList(maps);
            }
            return this.obj;
        } else if (this.obj instanceof List) {//list集合
            List<Map<String, Object>> list;
            List<Object> obj = (List<Object>) this.obj;
            if (obj!=null && obj.size()>0) {
                if ((obj.get(0) instanceof Map)) {
                    list = (List<Map<String, Object>>) this.obj;

                } else {
                    list = BeanKit.listToMapList(obj);
                }
                wrapTheMapList(list);
                this.obj=list;
            }
            return this.obj;
        } else if (this.obj instanceof Map) {//Map
            Map<String, Object> map = (Map<String, Object>) this.obj;
            wrapTheMap(map);
            return map;
        } else {//普通对象
            Map<String,Object> map =   BeanKit.beanToMap(this.obj);
            wrapTheMap(map);
            return map;
        }
    }

    /**
     * 单个数据挖取
     * @param map
     */
    protected abstract void wrapTheMap(Map<String, Object> map);

    /**
     * 批量集合挖取
     * @param list
     */
    protected abstract void wrapTheMapList(List<Map<String, Object>> list);
}
